function colorToRGB(val) {
	var re_hex = /^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/i;
	if(re_hex.exec(val)) {
  	val = [
    	parseInt(RegExp.$1, 16),
      parseInt(RegExp.$2, 16),
      parseInt(RegExp.$3, 16)
     ].join(', ');
   }
   return val;
}

function TableMouseOver(Obj) {
	if(!Object.isElement(Obj)) return;
	var f_input = Obj.getElementsByTagName('input')[0];
	// 为搜索显示的控制
	try {
		if (!Obj.id && Obj.previousSibling.getElementsByTagName('input')[0].checked) return false;
	} catch(e) {}
	if(f_input && f_input.checked) {
		return false;
	} else {
		Element.addClassName(Obj, 'item_over');
	}
}
function TableMouseOut(Obj) {
	if(!Object.isElement(Obj)) return;
	var f_input = Obj.getElementsByTagName('input')[0];
	try {
		if (!Obj.id && Obj.previousSibling.getElementsByTagName('input')[0].checked) return false;
	} catch(e) {}
	if(f_input && f_input.checked) {
		return false;
	} else {
		Element.removeClassName(Obj, 'item_over');
	}
}

function getBrowserVersion() {
	try {
		var userAgent = navigator.userAgent.toLowerCase();
		return (userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [])[1];
	} catch(e) {
		return 0;
	}
}

// 关闭页面之前的提示信息
window.onload = function(event) {
	window.onbeforeunload = function(event) {
		var _event = function(){
			//将用户行为发送出去
			_do_logout = true;
			jsoplog.ucCapture('closebutton');
			jsoplog.sendStay();
			_do_logout = false;
		};
		try {
			event = window.event || event;
			var _write_info = ' ------------------------------------ \n\n 您正在写信状态，确定要关闭当前页面吗？\n\n ------------------------------------ ',
			_writecard_info = ' ----------------------------------------- \n\n 您正在制作明信片状态，确定要关闭当前页面吗？\n\n ----------------------------------------- ';
			if (writemail.isChanged() && DOM.composeMail.visible() && !_do_logout) {
				try {
					event.returnValue = _write_info;
				} catch(e) {
					return _write_info;
				}
				return _write_info;
			}
			if(writecardmail.isChanged() && DOM.composeCardMail.visible() && !_do_logout) {
				try {
					event.returnValue = _writecard_info;
				} catch(e) {
					return _writecard_info;
				}
				return _writecard_info;
			}
			_event();
		} catch (e) {}
	};
};

// 退出系统的时候清空掉所有的由于闭包可能产生的内存泄露问题
window.onunload = function() {
	try {
		hiddenAllPanel();
	} catch(e) {}
	try {
		// mailAddressClass.destroy();
	} catch(e) {}
	try {
		var _dom_event = ['click', 'mouseover', 'mouseout'];
		for(var key in DOM) {
			if (DOM[key]) {
				_dom_event.each(function(item) {
					try {
						Event.stopObserving(DOM[key], item);
					} catch(e) {}
				});
			}
		}
	} catch(e) {}
	try {
		var _event = ['onload', 'onresize', 'onbeforeunload', 'onunload'];
		_event.each(function(item) {
			if(typeof window[item] == 'function') window[item] = null;
		});
		if(wresize) wresize.destroy();
	} catch(e) {}
};

// 退出系统
var _do_logout = false;
function doLogout() {
	try {
            mailfolder.close_browser();
	} catch(e) {}
	var confunc = function() {
		try {
			_do_logout = true;
        	//将用户行为发送出去
        	//标注用户要登出
			PassportSC.logoutRedirectUrl = 'http://mail.' + localDomain;
       		jsoplog.ucCapture('logout');
       		jsoplog.sendStay();
    		PassportSC.logoutHandle(document.body, function(){}, function(){
				var rdurl = USE_SYS.name == 'vip.sohu' ? USE_SYS.protocol + '//vip.' : USE_SYS.protocol + '//mail.'
				window.top.location.href = rdurl + localDomain;
    			// window.top.location = 'http://mail.' + localDomain;
    		});
    	} catch(e) {}
	};
	var _write_info = '您正在写信状态，确定要关闭当前页面吗？',
		_writecard_info = '您正在制作明信片状态，确定要关闭当前页面吗？';
	if (writemail.isChanged() && DOM.composeMail.visible()) {
		_dialog.confirm({info: _write_info, click: function() {
			confunc();
		}});
		return false;
	}
	if(writecardmail.isChanged() && DOM.composeCardMail.visible()) {
		_dialog.confirm({info: _writecard_info, click: function() {
			confunc();
		}});
		return false;
	}
	confunc();
}

function reAutoLists() {
	return recentLists.concat(contactLists);
}

// 动态加载script标签内容
if(typeof loadScript != 'function')
var loadScript =  function(src, callback, charset) {
	var script = document.createElement('script');
	script.setAttribute('language', 'javascript');
	if (charset) script.setAttribute('charset', charset);
	script.setAttribute('src', src);
	var obj = document.body ? document.body : document.getElementsByTagName('head')[0];
	obj.appendChild(script);
	if(document.all) {
		script.onreadystatechange = function() {
			if(this.readyState == 4 || this.readyState == 'complete' || this.readyState == 'loaded') {
				callback();
			}
		};
	} else {
		script.onload = function() {
			callback();
		};
	}
};

//获取浏览器的宽和高
function getWindowDimensions() {
	var _h = (document.compatMode != 'BackCompat' ? document.documentElement.clientHeight : document.body.clientHeight) || 0;
	var _w = (document.compatMode != 'BackCompat' ? document.documentElement.clientWidth : document.body.clientWidth) || 0;
	return {"win_width": _w, "win_height": _h};
}


// 为了便于生成图片的分类，重新组织明信片的数据结构
function reBuildPostcardData(ret) {
	if(CARDLIST != '') return;
	var _CARDLIST = [];
	POSTCARDSEQ.each(function(item, index) {
		ret.each(function(_item) {
			if(_item.type == item.type) {
				if(!_CARDLIST[index]) _CARDLIST[index] = [];
				_CARDLIST[index].push(_item);
			}
		});
	});
	CARDLIST = _CARDLIST.toJSON();
}


// 根据url后面的参数直接进入到邮件的列表，写信界面
function getPanelByUrl(onload) {
	var curl = window.location.href, c = curl.split('#');
	if(!onload) {
		try {
			if (c[1]) {
				var spn = ['mailList_', 'writeMail', 'userMail', 'postcardMail', 'readMail_'], _flag = false;
				spn.each(function(item){
					try {
						if (c[1].include(item)) _flag = true;
					} catch(e) {}
				});
				if (_flag) return;
			}
			try {
				(DOM.mainPage = DOM.mainPage ? DOM.mainPage : $('mainPage')).show();
				deleteLoadPage();
			} catch (e) {}
			return;
		} catch(e) {}
	}
	
	var getPanel = [
		{name: 'mailList_1',   event: function() {
			// 当登录的时候载入的是‘收件箱’页面，开始从缓存中查找（载入邮箱的时候会对收件箱首页进行预载入）
			var _idx = 0;
			(function() {
				try {
					var _j = (function() {
						try {
							if (isConferenceMode) {
								var _lc = mailConference.getListCache(1, 1);
								return _lc && _lc.length > 0;
							} else {
								return mailList.mailListCache && typeof mailList.mailListCache['inbox1'][mailList.currentPage] != 'undefined';
							}
						} catch(e) {
							return false;
						}
					})();
					if (_j) {
						changePanel('mailList', 1);
					} else {
						var CF = arguments.callee;
						var _t = setTimeout(function(){
							clearTimeout(_t);
							_t = null;
							if(_idx > 20) {
								changePanel('mailList', 1);
								_idx = null;
								return false;
							}
							CF();
							_idx ++;
						}, 100);
					}
				} catch(e) {}
			})();}
		},
		{ name: 'mailList_-2',  event: function() { changePanel('mailList', -2); } },
		{ name: 'writeMail',    event: function() { changePanel('composeMail'); } },
		{ name: 'userMail',     event: function() { changePanel('userMail'); } },
		{ name: 'addPopAccount',event: function() { changePanel('addPopAccount'); } },
		{ name: 'postcardMail', event: function() { changePanel('composeCardMail'); } },
		{ name: 'readMail_',    event: function() {
			if(arguments.length > 0) var u = arguments[0];
			var mid = u.split("_");
			mid = parseInt(mid[1]);
			if (isConferenceMode) {
				mailConference.getMailList(null, null, null, function(ret){
					this.cacheList = ret;
					for (var i = 0; i < this.cacheList.length; i++) {
						if (this.cacheList[i].thread == mid) {
							this.getMailRead(mid);
							return false;
						}
					}
					changePanel('mainPage');
				}.bind(mailConference));
			} else {
				mailList.currentFolder = 1;
				mailList.getMailPage(mailList.currentFolder, 0, function(ret){
					mailRead.cacheList = ret;
					_currentPageFolderList = ret;
					for (var i = 0; i < _currentPageFolderList.length; i++) {
						if (_currentPageFolderList[i].rowid == mid) {
							mailRead.getMailRead(mid);
							return false;
						}
					}
					changePanel('mainPage');
				});
			}
		}}
	];
	var _load = false;
	if (c[1] && !c[1].include('mailMain')) {
		getPanel.each(function(item){
			if (c[1].include(item.name)) {
				try {
					item.event(c[1]);
				} catch (e) {}
				_load = true;
			}
		});
	}
	if(_load) return;
	if(isDefaultListPage) {
		isDefaultListPage = false;
		getPanel[0].event();
		return;
	}
	deleteLoadPage();
	changePanel('mainPage');
}

// 邮箱登录载入成功之后，删除载入页面...
function deleteLoadPage() {
	var _sml = $('sohuMailMainLoading'), _smm = $('sohuMailMain');
	try {
		if(_sml.visible()) _sml.hide();
	} catch(e) {}
	try {
		if(!_smm.visible()) _smm.show();
	} catch(e) {}
}

// 重置整个页面的宽度
function resizeBody() {
	var _cw = getBodyWidth(),
	_b_width = _cw - staticValue.scrollBar;
	if(!DOM.currentBody) DOM.currentBody = $('currentBody');
	if(!DOM.navbg) DOM.navbg = $('navbg');
	if(!DOM.left) DOM.left = $('left');
	if(!DOM.left_bottom_bg) DOM.left_bottom_bg = $('left_bottom_bg');
	if(DOM.currentBody) {
		DOM.currentBody.setStyle({width : _b_width + 'px'});
		var isie6 = getBrowserVersion().include('6.0'),
			_h = document.body.clientHeight,
			_h = _h > 560 ? _h : 560,
			_rh = (DOM.navbg.getHeight() + DOM.left.getHeight() + DOM.left_bottom_bg.getHeight() + 20),
			_h = _h > _rh ? _h : _rh;
		if(isie6) {
			DOM.currentBody.setStyle({height:_h + 'px'});
		} else {
			DOM.currentBody.setStyle({minHeight:_h + 'px'});
		}
	}
	if(!DOM.navbg) DOM.navbg = $('navbg');
	if(DOM.navbg) {
		DOM.navbg.setStyle({width:_b_width + 'px'});
	}
}

// 重置右侧页面高度
function resizeRightHeight() {
	DOM.right_content.setStyle({
		height: DOM.left.getHeight() + 'px'
	})
}

// 重置右侧栏宽度
function resizeRightPanel() {
	var _right_width = getRightPanelWidth();
	/*
	var right = document.getElementsByClassName(className);
	for (var i = 0; i < right.length; i++) {
		if(mailConference._mail_content_is_max) continue;
		Element.setStyle(right[i], {width : _right_width + 'px'});
	}
	*/
	if(!DOM.right) DOM.right = $('right');
	if(DOM.right) {
		DOM.right.setStyle({width : _right_width + 'px'});
	}
	if(!DOM.readMail) DOM.readMail = $('readMail');
	if(DOM.readMail) {
		DOM.readMail.setStyle({width: _right_width - getMainSpaceWidth() + 'px'});
	}
	resizeWriteAreaHeight();
}

// 载入的时候就进行一次页面的大小重置
(function() {
	resizeRightPanel();
})();

function getMainSpaceWidth() {
	return staticValue.space.outer_lf + staticValue.space.outer_rt + staticValue.space.inner_lf + staticValue.space.inner_rt;
}

function resizeOtherItem() {
	// 写信区域内容size重绘
	var _rpw = getRightPanelWidth() - getMainSpaceWidth();
	var _wdw = staticValue.writeAddrWidth;
	if(!DOM._wa) DOM._wa = $('writemail_area');
	if (DOM._wa) {
		try {
			DOM._wa.setStyle({
				width: (_rpw - _wdw) + "px",
				height: "100%"
			});
		} catch(e) {}
	}
	if(!DOM._wca) DOM._wca = $('writecardmail_area');
	if(DOM._wca) {
		Element.setStyle(DOM._wca, {
			width : (_rpw - _wdw) + "px",
			height : "100%"
		});
		if(!DOM._upi) DOM._upi = $('upload_photo_info');
		Element.setStyle(DOM._upi.parentNode.parentNode, {width: (_rpw - 230) + "px"});
		Element.setStyle(DOM._upi.parentNode, {width: (_rpw - 250) + "px"});
	}
	
	// 信纸区域的宽度重置
	try {
		if (!DOM._letter) DOM._letter = $('letter_area');
	} catch(e) {}
	if(DOM._letter) {
		try {
			DOM._letter.setStyle({
				width: (_rpw - _wdw - 86 - 30 - 20) + 'px'
			});
		} catch(e) {}
	}
	
	// 明信片区域的宽度重置
	try {
		if(!DOM._card_parea) DOM._card_parea = $('card_parent_area');
	} catch(e) {}
	if(DOM._card_parea) {
		try {
			DOM._card_parea.setStyle({
				width: (_rpw - _wdw - 30 - 100 - 20) + 'px'
			});
		} catch(e) {}
	}
	
	// 文本编辑器的宽度
	if (!DOM._edtm) 
			DOM._edtm = $("editor.mess2");
	if (DOM._edtm) {
		Element.setStyle(DOM._edtm, {
			width: _rpw - _wdw - 10 - 10 - 20 + "px"
		});
	}
	
	// 重绘会话内容区域
	DOM._dlg_rd = $('dialog_read_hide');
	if (DOM._dlg_rd && !mailConference._mail_content_is_max) {
		DOM._dlg_rd.setStyle({
			width : (_rpw - staticValue.rightAdsWidth) + "px"
		});
	}
	
	// 重绘地址薄内容宽度
	if(!DOM._al) DOM._al = $("mail_address_right");
	if (DOM._al) {
		DOM._al.setStyle({
			width : (_rpw - 194) + "px"
		});
	}
    //重绘传情计划的页面
	if(!DOM._cwa) DOM._cwa = $( "customWriteArea" );
    if (DOM._cwa) {
        DOM._cwa.setStyle({
			width : (_rpw - _wdw) + "px"
        });
    }
	if(!DOM._cd) DOM._cd = $("customDesc");
    if(DOM._cd){
        DOM._cd.setStyle( {
			width : (_rpw - 380) + "px"
        });
    }
}

// 重置写信页面信件编辑区域高度
function resizeWriteAreaHeight() {
	try {
		var rightAreaHeight = getRightPanelHeight(),
			writeAreaHeight = rightAreaHeight - 160;
		if(!DOM.address) DOM.address = $('address');
		DOM.address.setStyle({height:rightAreaHeight + 'px'});
		if (!DOM._edt) 
			DOM._edt = $('ineditor');
		if (DOM._edt) {
			Element.setStyle(DOM._edt, {
				height: writeAreaHeight + 'px'
			});
			try {
				if (DOM._edt.firstChild.lastChild) {
					Element.setStyle(DOM._edt.firstChild.lastChild, {
						height: (writeAreaHeight - 30) + 'px'
					});
				}
			} 
			catch (e) {
			}
		}
		if (!DOM._edtm) 
			DOM._edtm = $('editor.mess2');
		if (DOM._edtm) {
			Element.setStyle(DOM._edtm, {
				height: (writeAreaHeight - 40) + 'px'
			});
		}
	} catch(e) {}
}

// 获取屏幕宽度
function getBodyWidth() {
	var cw = window.document.body.clientWidth;
	// 留了10个像素，为了IE的边
	return cw < 1020 ? 1020 : cw;
}

function getRightPanelWidth() {
	var cw = getBodyWidth() - staticValue.space.body_lf - staticValue.space.body_rt;
	return cw - staticValue.leftWidth - staticValue.scrollBar;
}

function getRightPanelHeight() {
	try {
		var wh = window.document.body.clientHeight;
		// if(DOM.left) DOM.left = $('left');
		// var lh = DOM.left.getHeight();
		if(wh > 0) {
			// if(DOM.left) {
			// 	return (wh - 164) > lh ? (wh - 164) : lh;
			// }
			
			var rh = wh - staticValue.topHeight - 20 - 36 - 60;
			// var rh = wh - 164;
			return (rh > 400) ? rh : 400;
		}
		return 0;
	} catch(e) {}
}

// 添加ajax的历史记录，（IE的历史记录采用单独的类库）
function addAjaxHistory(key, value, title, rsh) {
	if (Prototype.Browser.IE) {
		// 关闭history，为了调试
		// setTimeout(function() {
			if (!rsh) {
				ajaxHistoryIE.add(key, value, title);
			} else {
				ajaxHistoryIE.title(title);
			}
		// }, 100);
	} else {
		// if(Prototype.Browser.WebKit) return;
		if (!rsh) {
			dhtmlHistory.add(key, value);
		}
		dhtmlHistory.setTitleContent(title);
	}
}

// 创建一个iframe用来检测css文件是否载入完成
// 原理：css文件中最后一个css属性是控制iframe大小的样式，当iframe改变大小，会触发onresize事件，由此可以知道css文件已经载入完成
(function() {
	var d = isDomain ? localDomain : null,
		setDm = d ? 'document.domain=\"' + d + '\";' : '';
	var _div = document.createElement('div');
	$(_div).setStyle({
		position:'absolute',
		top:'-10000px',
		left:'-10000px'
	}).innerHTML = '<iframe id="listener_css_loaded" name="listener_css_loaded" class="listener-css-loaded"></iframe>';
	document.body.appendChild(_div);
	$('listener_css_loaded').src = 'javascript:document.open();document.write(\'<html><head><script>'+ setDm +'</script></head><body></body></html>\');document.close();';
})();

function changeMailSkin(skin) {
	(function() {
		var _css = $('mail_main_css'), _css_url = _css.href,
			mg = mailCfgClass.getProfileContent(), _cs = 'blue';
		if(mg.user_skin) var _cs = mg.user_skin;
		var _new_url = _css_url.replace(_cs, skin);
		// _css.href = _new_url;
		
		(function() {
			var _div = document.createElement('div');
			_div.id = 'css_loaded_iframe';
			$(_div).setStyle({
				top:'-1000px',
				left:'-1000px',
				width:'10px',
				height:'10px',
				position:'absolute',
				zIndex:1
			}).innerHTML = '<iframe src="javascript:document.open();document.write(\'<html><head><link href='+ _new_url +' rel=stylesheet /></head><body></body></html>\');document.close();" onload="cssLoadedCallback(\'mail_main_css\', \''+ _new_url +'\', \''+ skin +'\');"></iframe>';
			document.body.appendChild(_div);
			Tips.show('载入中，请稍候...');
		})();
		mg.user_skin = skin;
	})();
}

// css 文件载入完成的callback函数
function cssLoadedCallback(css, url, skin) {
	$(css).href = url;
	var ifr = $('listener_css_loaded'), ifrw = ifr.document ? ifr : ifr.contentWindow;
	if(Prototype.Browser.Opera) ifrw = ifr.contentWindow;
	ifrw.onresize = function(){
		// fn(window.parent);
		var p = window.parent;
		p.staticValue.reset_space();
		p.resizeBody();
		p.resizeRightPanel();
		p.resizeRightHeight();
		p.resizeOtherItem();
		p.profile_set({user_skin:skin});
		// p.$('css_loaded_iframe').remove();
		var rd = p.document.getElementById('css_loaded_iframe');
		if(rd) rd.parentNode.removeChild(rd);
		p.Tips.hide();
	};
}

function loadPassportGroup() {
	// 不在用passport中取出的数据了
	return;
	/*
	var PPservice = PassportSC.cookie['service'];
	var PPservceValid = [];
	var PPservceValid2 = [];
	for (var el in PPservice) {
		if (PPservice[el] == 1) {
			var obj = {
				name : PassportSC.appName[el],
				url : PassportSC.appUrl[el]
			};
			PPservceValid[PPservceValid.length] = obj;
		} else {
			
			var obj2 = {
				name : PassportSC.appName[el],
				url : PassportSC.appUrl[el]
			};
			PPservceValid2[PPservceValid2.length] = obj2;
		}
	}
	var a = [];
	a.push('<li><a hidefocus="true" href="http://www.sohu.com" target="_blank" style="color:white;">搜狐首页</a></li>');
	var len = PPservceValid.length;
	var max = 2;
	var maxLen = (len > max) ? max : len;
	for (var i = 0; i < maxLen; i++) {
		var obj = PPservceValid[i];
		a.push(['<li style="color:white;">|</li><li><a hidefocus="true" href="',
				obj.url,
				'" target="_blank" style="color:white;">',
				obj.name,
				'</a></li>'].join(''));
	}
	if((max-len) > 0) {
		var P2 = [];
		for(var i=0;i<(max-len);i++) {
			var p2len = PPservceValid2.length;
			var index = Math.floor(Math.random() * p2len);
			P2.push(PPservceValid2[index]);
			PPservceValid2.splice(index, 1);
		}
	}
	a.push('<li style="color:white;">|</li><li><a hidefocus="true" href="http://blog.sohu.com/camp?from=1000" target="_blank" style="color:white;">白社会</a></li>');
	if (maxLen == 0) {
		a = [];
		a.push('<font color="white">仅有邮箱还不够，更多精彩尽在</font><a hidefocus="true" href="http://blog.sohu.com/camp?from=1000" target="_blank" style="color:white;">白社会</a>');
	} else if((max-len) > 0) {
		var P2 = [];
		for(var i=0;i<(max-len);i++) {
			var p2len = PPservceValid2.length;
			var index = Math.floor(Math.random() * p2len);
			P2.push(PPservceValid2[index]);
			PPservceValid2.splice(index, 1);
		}
		for(var j=0;j<P2.length;j++) {
			a.push(['<li style="color:#DEDEDE;">|</li>',
					'<li><a hidefocus="true" href="',
					P2[j].url,
					'" target="_blank" style="color:#DEDEDE;">',
					P2[j].name,
					'</a></li>'].join(''));
		}
	}
	var b = '<li style="margin:0px;"><input type="hidden" name="ie" value="utf8"/><input id="sogouInput" name="query" type="text" class="input s_search_input" /></li>'+
			'<li style="margin:0!important;margin:1px 0 0 0"><input id="sogouInputBt" type="button" class="amb search s_search_button" />'+
			'<div id="searchInputBt" style="display:none;"><input type="button" class="amb search-mail s_search_mail"><input type="button" class="amb search-other s_search_other">'+
			'</div></li>';
	var cr_content = '<li style="color:white;"><a style="color:white;" target="_blank" href="http://class.chinaren.com/">校友录</a></li><li style="color:white;">|</li>'+
					 '<li style="color:white;"><a style="color:white;" target="_blank" href="http://club.chinaren.com/">社区</a></li><li style="color:white;">|</li>'+
					 '<li style="color:white;"><a style="color:white;" target="_blank" href="http://campus.chinaren.com/">校园</a></li><li style="color:white;">|</li>'+
					 '<li style="color:white;"><a style="color:white;" target="_blank" href="http://i.chinaren.com/group">群组</a></li><li style="color:white;">|</li>'+
					 '<li style="color:white;"><a style="color:white;" target="_blank" href="http://i.chinaren.com/">空间</a></li>',
	sg_content = '<li style="color:white;"><a style="color:white;" target="_blank" href="http://bbs.sogou.com/">说吧</a></li><li style="color:white;">|</li>'+
				 '<li style="color:white;"><a style="color:white;" target="_blank" href="http://wenda.sogou.com/">问答</a></li><li style="color:white;">|</li>'+
				 '<li style="color:white;"><a style="color:white;" target="_blank" href="http://mbox.sogou.com/">音乐盒</a></li>',
	c = USE_SYS.name == 'sohu' ? [a.join(''), b].join('<br />') : USE_SYS.name == 'chinaren' ? [cr_content, b].join('<br />') : USE_SYS.name == 'sogou' ? [sg_content, b].join('<br />') : '';
	// $('nav_passport_group').innerHTML = c;
	$('pp_group').innerHTML = USE_SYS.name == 'sohu' ? a.join('') : USE_SYS.name == 'chinaren' ? cr_content : USE_SYS.name == 'sogou' ? sg_content : '';
	*/
}


// 定义一个全局的flag, 当有AJAX交互的时候，这个flag设置为true, 防止界面上的提交按钮重复提交
var global_flag = false;
var flagHandler = {
	onCreate : function() {
		global_flag = true;
		try {
			if(mailUploadFile.uploading) {
				return false;
			}
		} catch(e) {}
		Tips.show('载入中，请稍候...');
	},
	onComplete : function() {
		global_flag = false;
		Tips.hide();
	}
};

/*
// 创建提示信息层
function createPromptInfo(_class) {
	try {
		var _div = document.createElement('div');
		_div.className = _class;
		_div.style.display = 'none';
		// _div.style.left = '5px';
		// _div.style.bottom = '28px';
		document.body.appendChild(_div);
		return _div;
	} catch(e) {}
}

var LoadingStatus = {
	init: function() {
		try {
			if (!DOM.loading) 
				DOM.loading = createPromptInfo('load');
		} catch(e) {}
	},
	show: function(msg) {
		try {
			DOM.loading &&
			(function(){
				msg ? DOM.loading.innerHTML = msg : DOM.loading.innerHTML = '载入中,请稍候...';
				Element.show(DOM.loading);
			})();
		} catch(e) {}
	},
	hide: function() {
		try {
			DOM.loading && Element.hide(DOM.loading);
		} catch(e) {}
	}
};

var MessagePanel = {};
Object.extend(MessagePanel, LoadingStatus);
MessagePanel.flag = false;
MessagePanel.show = function(msg, prt) {
	this.flag = true;
	try {
		DOM.loading &&
		(function(){
			msg ? DOM.loading.innerHTML = msg : DOM.loading.innerHTML = '载入中,请稍候...';
			Element.show(DOM.loading);
		})();
	} catch(e) {}
	if(prt) return false;
	try {
		var self = this;
		var _t = setTimeout(function() {
			clearTimeout(_t);
			_t = null;
			self.hide();
		}, 10000);
	} catch(e) {}
};
MessagePanel.hide = function() {
	this.flag = false;
	try {
		DOM.loading && Element.hide(DOM.loading);
	} catch(e) {}
};
*/


var Tips = {
	flag:false,
	tipsdiv:null,
	content:null,
	text:'',
	isshow:false,
	createDiv: function() {
		this.tipsdiv = $('tips_ct');
		this.content = $('tips_ct_info');
		return this.tipsdiv;
	},
	/*
 	 * arguments[0]: string -> 提示信息内容
 	 * arguments[1]: number -> 提示信息停留时间
 	 */
	show: function() {
		var a1 = arguments[0], a2 = arguments[1], a3 = arguments[2];
		a1 = !a3 ? (this.text != '' ? this.text : a1) : a1;
		if(this.flag || !a1 || a1 == '') return false;
		if(!this.tipsdiv) this.tipsdiv = this.createDiv();
		this.tipsdiv.show();
		this.isshow = true;
		var _j = (a2 != undefined && typeof a2 == 'number');
		a1 = '<div class="txt">' + a1 + '</div>';
		if(!_j) a1 = '<div class="f-lf im-wp"><img src="'+ MailConst.IMG +'/loading.gif" /></div><div class="f-lf txt">' + a1 + '</div>';
		this.content.innerHTML = a1;
		var self = this;
		if (a3) {
			this.flag = true;
			setTimeout(function() {
				self.flag = false;
			}, 3000);
			return false;
		}
		if(_j) {
			this.flag = true;
			var _t = setTimeout(function() {
				clearTimeout(_t);
				_t = null;
				self.flag = false;
				self.hide();
			}, (a2*1000));
		}
	},
	hide: function() {
		this.text = '';
		if(this.flag) return false;
		this.tipsdiv.hide();
		this.isshow = false;
	}
};


var panelObjList = [
	{name: "mainPage",             id: null,   panelid: "mainPage",              show: false,   exec: function(r){mailMainPage(r);}},
	{name: "mailList",             id: null,   panelid: "mailList",              show: false,   exec: function(need_callback, r){mailList._is_rsh = r;if(need_callback)ML(mailStarList.reset_selected);}},
	{name: "mailSearch",           id: null,   panelid: "mailSearch",            show: false,   exec: function(r){}},
	{name: "composeMail",          id: null,   panelid: "composeMail",           show: false,   exec: function(r, i){writemail.writeNewMail(r, i);}},
	{name: "draftToComposeMail",   id: null,   panelid: "composeMail",           show: false,   exec: function(r){}},
	{name: "composeCardMail",      id: null,   panelid: "composeMail",       	 show: false,   exec: function(r){writecardmail.init(r);}},
	{name: "newFolderList",        id: null,   panelid: "newFolderList",         show: false,   exec: function(r){mailList.initFolderDetails(r);}},
	{name: "addFolderList",        id: null,   panelid: "newFolderList",         show: false,   exec: function(r){mailList.initFolderDetails(r, true);}},
	{name: "popManage",            id: null,   panelid: "newFolderList",         show: false,   exec: function(r){mailPop.getPop3List();}},
	{name: "popCreate",            id: null,   panelid: "newFolderList",         show: false,   exec: function(r){mailPop.setPop3Account();}},
	{name: "self",                 id: null,   panelid: "",                      show: false,   exec: function(r){mailList.initFolderDetails(r);}},
	{name: "contactList",          id: null,   panelid: "addressGroupList",      show: false,   exec: function(r){mailAddressClass.init(r);}},
	{name: "contactCate",          id: null,   panelid: "addressGroupList",      show: false,   exec: function(r){mailAddressClass.initGroup(this.id, r);}},
	{name: "mobileConfiguration",  id: null,   panelid: "mobileConfiguration",   show: false,   exec: function(r){mobileCfg.getMobile();}},
	{name: "wapConfiguration",     id: null,   panelid: "mobileConfiguration",   show: false,   exec: function(r){mobileCfg.initWap();}},
	{name: "rss",                  id: null,   panelid: "",                      show: false,   exec: function(r){window.open('http://reader.mail.sohu.com');}}, 
	{name: "score",                id: null,   panelid: "",                      show: false,   exec: function(r){window.open('http://goto.mail.sohu.com/goto.php3?code=dianjifen070406');}}, 
	{name: "card",                 id: null,   panelid: "",                      show: false,   exec: function(r){window.open('http://ecard.mail.sohu.com/card/index.jsp?from=mail');}}, 
	{name: "service",              id: null,   panelid: "",                      show: false,   exec: function(r){window.open('http://me.sohu.com/online_service.jsp?pid=9');}},
	{name: "mailConfiguration",    id: null,   panelid: "mailConfiguration",     show: false,   exec: function(r){mailCfgClass[this.id](r);}},
	{name: "sendSuc",              id: null,   panelid: "sendSuc",               show: false,   exec: function(r){sendSuccess();}},
	{name: "readMail",             id: null,   panelid: "readMail",              show: false,   exec: function(r){}},
	{name: "folderLock",           id: null,   panelid: "lockFolder",            show: false,   exec: function(r){mailfolder.initUI();}},
	{name: "userMail",             id: null,   panelid: "composeMail",           show: false,   exec: function(r){custom_mail_display.initConfPage(r);}}
];

var change_panel_flag = false;
function changePanel(panelName, panelID, isRsh, isSave, isInvite) {
	// isSave: 新添加的一个是否保存信件的参数 （2009-08-27）
	// 判断是否从写信页面离开
	try {
		for(var i=0,len=panelObjList.length;i<len;i++) {
			var e = panelObjList[i];
			try {
				if(e.show == true && (e.name == 'composeMail' || e.name == 'draftToComposeMail')) {
					if (!writemail.exit()) {
						var _info = isSave ? '您正在编辑的邮件将保存为草稿。确定要继续吗？' : '您确定放弃对此信件的操作吗？';
						_dialog.confirm({info: _info, click: function(event) {
							change_panel_flag = true;
							try {
								if(isSave) clickStore();
							} catch(e) {}
							// mail_signature=0;
							if (writemail.thisCurrentMailisSending) {
								if (__AJAX != null) {
									try {
										writemail.thisCurrentMailisSending = false;
										__AJAX.transport.abort();
										__AJAX = null;
									} catch(e) {}
								}
								removeDiv4Sending();
							}
							writemail._clear();
							_changed_panel(panelName, panelID, isRsh, isInvite);
							change_panel_flag = false;
						}});
						if(!change_panel_flag) return;
					} else {
						change_panel_flag = false;
					}
				}
				if(e.show == true && e.name == 'composeCardMail' && writecardmail.sendSuc == false) {
					if(writecardmail.isChanged()) {
						_dialog.confirm({info: '您确定放弃对此明信片的操作吗？', click: function(event) {
							_changed_panel(panelName, panelID, isRsh);
							change_panel_flag = false;
						}});
						if(!change_panel_flag) return;
					} else {
						change_panel_flag = false;
					}
				}
				if(e.show == true && e.name == 'userMail'){
					custom_mail_display.exit();
				}
				if(e.show == true && e.name == 'readMail') {
					var rpltxt = $('reply_textarea');
					if(rpltxt && rpltxt.value != "" && !rpltxt.value.startsWith("快速回复给：")) {
						_dialog.confirm({info: '您确定要放弃回复邮件吗？', click: function(event) {
							_changed_panel(panelName, panelID, isRsh);
							change_panel_flag = false;
						}});
						if(!change_panel_flag) return;
					} else {
						change_panel_flag = false;
					}
					if(mailConference._editor_content_change()) {
						_dialog.confirm({info: '您的邮件正处于编辑状态，您确定要放弃吗？', click: function(event) {
							_changed_panel(panelName, panelID, isRsh);
							change_panel_flag = false;
						}});
						if(!change_panel_flag) return;
					} else {
						change_panel_flag = false;
					}
				}
				if(e.name != 'mailList') {
					try {
						mailList.resetOrder();
					} catch(e) {}
				}
				if(e.name != 'mailSearch') {
					try {
						mailSearch.resetOrder();
					} catch(e) {}
				}
			} catch(e) {}
		} 
	} catch(e) {}
	_changed_panel(panelName, panelID, isRsh, isInvite);
}

function _changed_panel(panelName, panelID, isRsh, isInvite) {
	try {
        var need_star_callback = 0;
		if(panelName == 'mailList') {
			mailConference.page = 1;
            need_star_callback = 1;
		}
		
        panelObjList.each(function(e){
            if (e.name == panelName) {
                if (panelID) {
                    e.id = panelID;
                    if (typeof(panelID * 1) == 'number') {
                        mailList.currentFolder = panelID;
                        if (panelName != 'readMail') 
                            mailList.currentPage = mailList._currentPage = 0;
                    }
                }
                try {
                    if (need_star_callback) {
                        e.exec(need_star_callback, isRsh, isInvite);
                    } else {
                        e.exec(isRsh, isInvite);
                    }
                } catch (e) {}
                e.show = true;
            } else {
                e.id = null;
                e.show = false;
            }
        });
	} catch(e) {}
}



function hiddenAllPanel() {
	try {
		if(Editor1) {
			Editor1.destroy();
			Editor1 = null;
		}
	} catch(e) {}
	try {
		mailList.stopStar();
	} catch(e) {}
	try {
		mailConference.stopStar();
	} catch(e) {}
	/*
	try {
		// _menu_event_list 不存在了
		mailConference._menu_event_list.each(function(item) {
			Event.stopObserving(item, 'click');
			$A(item.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('*')).each(function(_item) {
				_item.onclick = null;
			});
		});
		mailConference._menu_event_list = [];
	} catch(e) {}
	*/
	try {
		for (var key in mailConference._editor) {
			if (mailConference._editor[key]) {
				mailConference._editor[key].destroy();
			}
		}
		mailConference._editor = {};
	} catch(e) {}
	try {
		for (var key in mailConference._upload) {
			if (mailConference._upload[key]) 
				mailConference._upload[key].destroy();
		}
		mailConference._upload = {};
	} catch(e) {}
	try {
		for (var key in mailConference._autocomplete) {
			if (mailConference._autocomplete[key]) {
				for (var _key in mailConference._autocomplete[key]) {
					if (mailConference._autocomplete[key][_key]) {
						mailConference._autocomplete[key][_key].destroy();
					}
				}
			}
		}
		mailConference._autocomplete = {};
	} catch(e) {}
	try {
		if(mailRead.menu) mailRead.menu['_closeMenu']();
	} catch(e) {}
	try {
		mailSearch.searchReadPanel = false;
	} catch(e) {}
	try {
		FloatADS.hide();
		var _fads = setTimeout(function() {
			clearTimeout(_fads);
			_fads = null;
			try {
				if(!DOM.composeMail || !DOM.mainPage) return;
			} catch(e) {
				return;
			}
			if(!DOM.composeMail.visible() && !DOM.mainPage.visible()) {
				FloatADS.show();
			}
		}, 500);
	} catch(e) {}
	try {
		if (!arguments[0]) {
			DOM.main_ad_area.removeClassName('cn1-adw');
			DOM.ad_main.hide();
		}
	} catch(e) {}
	try {
		// 解决在IE6下面的一个bug:当有float样式存在的时候，父节点高度为零，这个问题已经通过clear:both样式解决；
		// 但是当此时父节点高度发生变化的时候，IE6下的高度不会随之改变，必须有一个界面渲染的动作发生，才会改变。。。
		// 不解其中的原因，w3c,msdn上都没有找到相关的解释，也许需要看一下IE6版本的Trident内核才能找到答案吧。。。
		var d = document.createElement('div');
		$(d).setStyle({
			width:'10px',
			height:'10px',
			position:'absolute',
			zIndex:'1',
			left:'-100px',
			top:'-100px'
		});
		document.body.appendChild(d);
		d.parentNode.removeChild(d);
		d = null;
	} catch(e) {}
	panelObjList.each(function(e) {
		try {
			if(e && e.panelid != "") {
				DOM[e.panelid] ? DOM[e.panelid].hide() : $(e.panelid).hide();
				if(e.panelid == 'readMail') {
					try {
						var _rmb1 = $('read_mail_bar1'), _drc = $('dialog_read'), _rmb2 = $('read_mail_bar2');
						if(_rmb1) _rmb1.innerHTML = '';
						if(_drc) _drc.innerHTML = '';
						if(_rmb2) _rmb2.innerHTML = '';
					} catch(e) {}
					return false;
				}
				if(e.panelid == 'mailList') {
					try {
						mailConference.stopListenPos();
					} catch(e) {}
					try {
						mailList.stopListScrollPos();
					} catch(e) {}
				}
				if(e.panelid == 'mainPage' || e.panelid == 'composeMail' || e.panelid == 'sendSuc' || e.panelid == 'addressGroupList') return;
				try {
					DOM[e.panelid].innerHTML = '';
				} catch(e) {}
			}
		} catch(e) {}
	});
}

// 左侧菜单样式的改变
function changeToolbarStyle(panelObj, id) {
	mailList.currentFolder = 0;
	if(id) mailList.currentFolder = id;
	if(!mailList.cfolder_focus) mailList.cfolder_focus = '';
	if(mailList.cfolder_focus == ('folder_' + id)) return false;
	var fitem = $(mailList.cfolder_focus);
	if(fitem) fitem.removeClassName('a-bg current');
	if (!id) {
		mailList.cfolder_focus = '';
		return false;
	}
	var c = 'folder_' + id;
	$(c).addClassName('a-bg current');
	mailList.cfolder_focus = c;
	return false;
}

/*
// 左侧写信、收信button的样式改变
function changeLeftButton(cname) {
	return false;
	if(!DOM.write_mail) DOM.write_mail = $('write_mail');
	if(!DOM.check_mail) DOM.check_mail = $('check_mail');
	if (!cname || cname == '') {
		$([DOM.write_mail, DOM.check_mail]).each(function(item){
			$(item).removeClassName('m-check-focus');
		});
		return false;
	}
	if (DOM.write_mail.className.include(cname)) {
		DOM.write_mail.addClassName('m-check-focus');
		DOM.check_mail.removeClassName('m-check-focus');
	} else if(DOM.check_mail.className.include(cname)) {
		DOM.write_mail.removeClassName('m-check-focus');
		DOM.check_mail.addClassName('m-check-focus');
	}
}
*/

// 转换邮件字节大小的函数
function strfsize(size) {
	var ords = "KMGTPE", i = 0, remain = 0;
	size = 0 + size;
	if (size < 0) return '0';
	if (size < 973) return '' + size;
	do {
		remain = size & 1023;
		size = parseInt(size / 1024);
		if (size < 973)
			break;
		i++;
	} while (true);
	if (size < 9 || (size == 9 && remain < 973)) {
		if ((remain = Math.floor(((remain * 5) + 256) / 512)) >= 10) {
			size++;
			remain = 0;
		}
		return '' + size + '.' + remain + ords.charAt(i);
	}
	if (remain >= 512) size++;
	return '' + size + ords.charAt(i);
}

// 转换时间函数
function strfTime(time) {
	var localeTime = new Date(time);
	var year = localeTime.getFullYear();
	var month = localeTime.getMonth()+1;
	var day = localeTime.getDate();
	var localeTimeTime = localeTime.toLocaleTimeString();
	if (localeTimeTime.indexOf(' ') != -1) {
		localeTimeTime = localeTimeTime.split(' ');
		localeTimeTime = localeTimeTime[0];
	}
	return [year, "年",  month, "月", day, "日  ", localeTimeTime].join('');
}

// 超大邮件载入完成之后，重新调整显示这个邮件iframe的大小
function resizeMailContent(ifr_id) {
	try {
		ifr_id = $(ifr_id), ifr_d = ifr_id.contentWindow.document,
		desh = ifr_d.documentElement.scrollHeight, deoh = ifr_d.documentElement.offsetHeight,
		bsh = ifr_d.body.scrollHeight, boh = ifr_d.body.offsetHeight,
		desw = ifr_d.documentElement.scrollWidth, deow = ifr_d.documentElement.offsetWidth,
		bsw = ifr_d.body.scrollWidth, bow = ifr_d.body.offsetWidth,
		_h = (ifr_d.compatMode.toLowerCase() != 'backcompat' ? Math.max(desh, deoh) : Math.max(bsh, boh)) || 0,
		_w = (ifr_d.compatMode.toLowerCase() != 'backcompat' ? Math.max(desw, deow) : Math.max(bsw, bow)) || 0;
		ifr_id.style.height = _h + staticValue.scrollBar + 'px';
		ifr_id.style.width = _w + 'px';
		/*
		var _sf = arguments.callee,
		_t = setTimeout(function() {
			clearTimeout(_t);
			_t = null;
			_sf(ifr_id);
		}, 100);
		*/
	} catch(e) {}
}

function jsOplogOut() {
    if( _do_logout == false ){
        return;
    }
    var cookiename = 'mc_jsstay';
    var d = new Date();
    var ds = "end|" + d.getTime();
    appendCookie(ds + '', cookiename + '');
}

function jsOplogexit(){
    if( _do_logout == false ){
        return;
    }
    var cookiename = 'mc_jsstay';
    var d = new Date();
    var ds = "exit|" + d.getTime();
    appendCookie( ds + '', cookiename + '' );
}

function jsOplogLogin(){
    var cookiename = 'mc_jsstay';
    var d = new Date();
    var ds = "start|" + d.getTime();
    appendCookie( ds + '', cookiename + '' );
}



var ALVA_UC = null;
var PVINSINGHT_NODE = null;
function cretePVPoint(){
    if(!PVINSINGHT_NODE) {
        PVINSINGHT_NODE = document.createElement('script');
        document.body.appendChild(PVINSINGHT_NODE);
    }
    return PVINSINGHT_NODE;
}
function createUCPoint(){
//创建隐藏的img，收集用户操作
    if( !ALVA_UC ){
        ALVA_UC = document.createElement('script');
        document.body.appendChild(ALVA_UC);
    }
    return ALVA_UC;
}

function startKeepAlive(){
	var excuter = new PeriodicalExecuter(function() {
    	jsoplog.sendPV('keepalive');
	}, IntervalConst.keepAlive);
}

function startJSOplog(){
	var excuter = new PeriodicalExecuter(function() {
    	jsoplog.sendUC();
	}, IntervalConst.sendJSOplog);
}

// ajax history for ie
// 为IE重写了ajax历史记录的类库
var ajaxHistoryIE = {
	map: {},
	ifr: null,
	loaded: false,
	isie6: getBrowserVersion().include('6.0'),
	init: function(domain) {
		// this.dm = domain;
		this.setDm = domain ? 'document.domain=\"' + domain + '\";' : '';
		var _body = document.body,
		// _iframe_history = "<iframe id='ajax_history_for_ie' name='ajax_history_for_ie' onload='ajaxHistoryIE.loaded=true;alert(\"init loaded\");' src='javascript:document.open();document.write(\"<html><meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\' /><head><script>"+ this.setDm +"</script></head><body></body></html>\");document.close();'></iframe>",
		_iframe_history = "<iframe id='ajax_history_for_ie' name='ajax_history_for_ie' onload='ajaxHistoryIE.loaded=true;'></iframe>";
		_div = document.createElement('div');
		Element.setStyle(_div, {
			display: 'none',
			left: '-2000px',
			top: '-2000px'
		});
		if(_body) {
			_body.appendChild(_div);
			_div.innerHTML = _iframe_history;
		} else {
			document.write(_iframe_history);
		}
		this.ifr = document.getElementById('ajax_history_for_ie');
		Element.setStyle(this.ifr, {
			position: 'absolute',
			left: '-1000px',
			top: '-1000px',
			width: '1px',
			height: '1px',
			zIndex: 999999,
			display: 'none'
		});
	},
	add: function(key, value, title) {
		this.map[key] = value;
		if(!this.isie6) window.location.hash = key;
		// alert(key + ':' + value + ':' + title);
		if (this.ifr) {
			this.ctrl = true;
			try {
				title = title.replace(/[\b\t\n\f\r\\]/g, '');
				this.ifr.src = 'javascript:document.open();document.write(\'<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><head><script>'+ this.setDm +'function pageloaded(){try{if(window.parent.ajaxHistoryIE){var P=window.parent.ajaxHistoryIE;P.callback("' + key + '");try{P.title("' + title + '");}catch(e){}try{document.title="'+ title +'";}catch(e){}if(P.ctrl)P.ctrl=false;}}catch(e){}}try{pageloaded();}catch(e){}<\/script></head><body onload=""></body></html>\');document.close();';
			} catch(e) {}
		}
	},
	title: function(title) {
		try {
			title = USE_SYS.titleident + ' - ' + title;
			document.title = title;
			if (this.ifr) 
				this.ifr.contentWindow.document.title = title;
		} catch(e) {}
	},
	callback: function(key) {
		if(this.ctrl) return;
		if(!this.isie6) window.location.hash = key;
		try {
			eval(this.map[key]);
		} catch(e) {}
	}
};

/******************************************************************/
// 判断邮件地址是否在联系人列表、最近联系人、白名单、黑名单中
function mailIsCacheList(mail, cacheList) {
	var _flag = false;
	cacheList.each(function(item) {
		if(item.email == mail) _flag = true;
	});
	return _flag
}

// 是否在地址簿联系人中
function mailIsContact(mail) {
	return mailIsCacheList(mail, contactLists);
}
// 是否在最近联系人中
function mailIsRecent(mail) {
	return mailIsCacheList(mail, recentLists);
}
// 是否在黑名单中
function mailIsBlack(mail) {
	if(mail == UserSohuID) return true;
	return mailIsCacheList(mail, blackLists);
}
// 是否在白名单中
function mailIsWhite(mail) {
	return mailIsCacheList(mail, whiteLists);
}
// 邮件地址是否在已接受邮件地址中，排重
function mailIsReceive(mail, r) {
	var _flag = false;
	r.each(function(item) {
		if(item[1].include(mail)) _flag = true;
	});
	return _flag;
}

/******************************************************************/


/******************************************************************/
// 发送、回复、转发的时候对邮件地址的一些格式化、过滤的函数
// 格式化邮件地址，返回的邮件地址列表，格式化为字符串
function format_mail(mail_list) {
	if(!mail_list && mail_list.length == 0) return '';
	var _t = [];
	mail_list.each(function(item) {
		if(!item[0].blank()) {
			var _a = '"'+ item[0] +'"<'+ item[1] +'>';
			if(_t.include(_a)) return;
			_t.push(_a);
		} else {
			if(_t.include(item[1])) return;
			_t.push(item[1]);
		}
	});
	return _t.join(', ');
}

// 如果reply_to存在，优先显示reply_to中的内容
function format_reply_to(mail) {
	var _rpl_to = [], _from = [];
	try {
		_rpl_to = mail.envelope.reply_to;
	} catch(e) {}
	try {
		_from = mail.envelope.from;
	} catch(e) {}
	return _rpl_to && _rpl_to.length > 0 ? _rpl_to : _from;
}

// 如果在收件人，抄送，密送中包含有自己的邮件地址，将其过滤掉
function format_filter(mail) {
	var _t = [];
	if(mail.length == 0) return _t;
	mail.each(function(item) {
		if(item[1] && !item[1].include(UserSohuID)) _t.push(item);
	});
	return _t;
}

// 过滤相同的邮件地址
function format_filter_same(mail_str) {
	if(typeof mail_str != 'string') return '';
	var _mail = mail_str.split(','), _new_mail = [];
	_mail.each(function(item) {
		if(item.blank()) return false;
		var _email = item;
		if(_email.include('<') && _email.include('>')) {
			_email = _email.slice(_email.indexOf('<')+1, _email.indexOf('>'));
		}
		_email = _email.strip();
		if(!_new_mail.join(',').include(_email)) {
			_new_mail.push(item);
		}
	});
	return _new_mail.join(',');
}
/******************************************************************/



/******************************************************************/
// 输入字符的全角转半角
function toTrimDBC(Str) {
	var DBCStr = "";
	for (var i = 0; i < Str.length; i++) {
		var c = Str.charCodeAt(i);
		if (c == 12288 || c == 32) {
			DBCStr += String.fromCharCode(32);
			continue;
		}
		if (c > 65280 && c < 65375) {
			DBCStr += String.fromCharCode(c - 65248);
			continue;
		}
		DBCStr += String.fromCharCode(c);
	}
	return DBCStr;
}

// 检查email地址的合法性 ------ update by fjc (2007-11-22)
function IsEmail(CheckEmail,flag) {
	if (CheckEmail == null || CheckEmail.strip() == "") {
		if(flag !== false)_dialog.alert({info: '请输入正确的邮箱地址，例如：abc@sohu.com'});
		return false;
	}
	var regm = /^[a-zA-Z0-9#._-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
	if (!CheckEmail.match(regm)) {
		if(flag !== false)_dialog.alert({info: '请输入正确的邮箱地址，例如：abc@sohu.com'});
		return false;
	} else {
		return true;
	}
}

// 检查是否包含特殊字符的判断
function checkSpecial(str, info) {
	if (Object.isNumber(str)) {
		str = str.toPaddedString(1);
	}
	if (str.strip() == "" || !str) {
		return true;
	}
	var _info = info ? info : '输入内容不能包含特殊字符';
	var regs = /[^\~\!\@\#\$\%\^\&\*\(\)\+\|\-\=\|\\\{\}\[\]\:\"\;\'\<\>\,\?\/]/;
	for (var i = 0; i < str.length; i++) {
		if (str.charCodeAt(i) > 255 || str.charCodeAt(i) < 0) {
			continue;
		} else if (!str.charAt(i) || typeof(str.charAt(i)) == "undefined"
				|| str.charAt(i).match(regs) == null) {
			_dialog.alert({info: _info});
			return false;
		}
	}
	return true;
}

// 返回限定长度的字符串
// 字符串中包含中文的字符长度（计算依照一个汉字相当于两个英文字符的长度）
function truncateIncludeCN(str, slen) {
	var len = str.length;
	var l = 0;
	var newStr = [];
	for (var i = 0; i < len; i++) {
		if (str.charCodeAt(i) > 255 || str.charCodeAt(i) < 0) {
			l += 2;
		} else {
			l++;
		}
		if (l < slen) {
			newStr.push(str.charAt(i));
		} else {
			newStr.push("...");
			break;
		}
	}
	return newStr.join("");
}
/******************************************************************/


/******************************************************************/
// 检查新邮件的定时器
// 判断是否可以从string转换成number的有效字符，或者直接就是number的格式
function strNumber(o) {
	return typeof (o*1) === 'number' && o != NaN;
}

// 检查新邮件的定时器
function checkNewMailCrontab() {
	var excuter = new PeriodicalExecuter(function() {
		checkNewMail();
	}, IntervalConst.checkNewMail);
}
function checkNewMail(user) {
	if(!user && mailUploadFile.uploading) {
		return;
	}
	var _t = strNumber(IntervalConst.timestamp) ? IntervalConst.timestamp : 0,
		_i = strNumber(IntervalConst.maxrowid) ? IntervalConst.maxrowid : 0;
	var params = {
		t: _t,
		i: _i
	};
	Tips.text = '正在收取邮件...';
	mail_check(params, checkNewMailCallBack.bind(checkNewMail, user));
}
// 初始化的时候检查一次新邮件
function checkNewMailCallBack(user, ret) {
	Tips.text = '';
	if(!Object.isArray(ret)) return false;
	if(ret.length < 4) return false;
	if(strNumber(ret[0])) IntervalConst.timestamp = ret[0];
	if(strNumber(ret[1])) IntervalConst.maxrowid = ret[1];
	if(ret[2] > 0 || user) {
		ret[2] = ret[2] ? ret[2] : 0;
		var _info = ret[2] > 0 ? '您有' + ret[2] + '封新邮件' : '您没有新邮件';
		Tips.show(_info, 8);
		if(!user && ret[2] > 0) {
			setTimeout(function() {
				newMailTipsRoll.start(ret[2]);
			}, 1000);
		}
		if (ret[3].folders && ret[3].folders.length > 0) {
			FolderList = mailConference.F.folders = ret[3].folders;
		}
		if (isConferenceMode) {
			mailConference.setConferenceNew(mailConference.F.folders);
		} else {
			mailList.refreshFolderListNewMail();
		}
		if(ret[2] > 0) {
			mailList.clearListCache();
			mailList.refreshListFlag = true;
			// 清掉会话相关的缓存
			mailConference.clearListCache();
		}
		if(ret[4] && ret[4].length > 0) {
			ret[4].each(function(item) {
				mailConference.clearThreadCache(item);
			});
		}
		if(!user && !(Element.visible(DOM.mailList) && (mailConference.folder == 1 || mailConference.folder == -2 || mailList.currentFolder == 1 || mailList.currentFolder == -2))) return;
		var j = (isConferenceMode ? (mailConference.folder == 1 || mailConference.folder == -2) : (mailList.currentFolder == 1 || mailList.currentFolder == -2)) && !DOM.readMail.visible();
		if(j) {
			mailConference.page = mailList.currentPage = mailList._currentPage = 0;
			// ML();
			changePanel('mailList', (mailConference.folder != 0 ? mailConference.folder : 1));
		} else {
			changePanel('mailList', (mailList.currentFolder != 0 ? mailList.currentFolder : 1));
		}
		/*
		if(user) {
			changeLeftButton('s_checkmail');
		}
		*/
	}
}
function initCheckNewMail() {
	var _t = strNumber(IntervalConst.timestamp) ? IntervalConst.timestamp : 0,
		_i = strNumber(IntervalConst.maxrowid) ? IntervalConst.maxrowid : 0;
	var params = {
		t: _t,
		i: _i
	};
	mail_check(params, function(ret) {
		if(!Object.isArray(ret)) return false;
		if(ret.length < 4) return false;
		if(IntervalConst.timestamp == 0) {
			FolderList = mailConference.F.folders = ret[3].folders;
		}
		if(strNumber(ret[0])) IntervalConst.timestamp = ret[0];
		if(strNumber(ret[1])) IntervalConst.maxrowid = ret[1];
		if (isConferenceMode) {
			mailConference.getMailList(1, 1, null, function(ret) {
				mailConference.setListCache(ret, 1, 1);
				mailConference.cacheList = ret;
			});
			mailConference.setConferenceNew(mailConference.F.folders);
		} else {
			mailList.preLoadedMailList(0, 1, function(ret) {
				mailRead.cacheList = ret;
			});
			mailList.refreshFolderListNewMail();
		}
	});
	DOM.sohuMailMain.observe('click', function(event) {
		newMailTipsRoll.revert();
	});
}

// 新邮件到达的title滚动提示
var newMailTipsRoll = {
	timer: null,
	origin_title: '',
	start: function(n) {
		var list1 = [
			'您有('+ n +')封新邮件. - 搜狐',
			'有('+ n +')封新邮件.您 - 搜狐',
			'('+ n +')封新邮件.您有 - 搜狐',
			'封新邮件.您有('+ n +') - 搜狐',
			'新邮件.您有('+ n +')封 - 搜狐',
			'邮件.您有('+ n +')封新 - 搜狐',
			'件.您有('+ n +')封新邮 - 搜狐',
			'.您有('+ n +')封新邮件 - 搜狐'
		], list2 = [
			'您有新邮件. - 搜狐',
			'有新邮件.您 - 搜狐',
			'新邮件.您有 - 搜狐',
			'邮件.您有新 - 搜狐',
			'件.您有新邮 - 搜狐',
			'.您有新邮件 - 搜狐'
		], list = (this.timer ? list2 : list1), len = list.length, index = 0, flag = false;
		if(!this.timer) this.origin_title = document.title;
		this.stop();
		var self = this;
		this.timer = setInterval(function() {
			if (flag && list.indexOf(document.title) == -1) {
				self.stop();
				return false;
			}
			if(index == len) index = 0;
			document.title = list[index];
			index++;
			flag = true;
		}, 500);
	},
	revert: function() {
		if(!this.timer) return;
		this.stop();
		if(this.origin_title != '') document.title = this.origin_title;
	},
	stop: function() {
		if(!this.timer) return;
		clearInterval(this.timer);
		this.timer = null;
	}
};

/******************************************************************/

// 向服务器端发送记录的时间
function sendLoadTime_debug() {
	var i = 0;
	var recfunc = function() {
		i++;
		var se = arguments.callee;
		if (RECORD_LOAD_TIME.length < 7) {
			var t = setTimeout(function(){
				clearTimeout(t);
				t = null;
				se();
			}, 1000);
		} else if(i > 30) {
			jsoplog.sendLoadProgress();
		} else {
			jsoplog.sendLoadProgress();
		}
	};
	recfunc();
	recfunc = null;
}

function showLoadTime_debug() {
	var _time = RECORD_LOAD_TIME[5] ? (RECORD_LOAD_TIME[5] - RECORD_LOAD_TIME[0]) : (RECORD_LOAD_TIME[RECORD_LOAD_TIME.length - 1] - RECORD_LOAD_TIME[0]);
	Tips.show('页面载入总共需要了' + _time + '毫秒', 5);
}

// 地址簿相关操作函数
// 当前的焦点输入框id
var src_focus_id = 'compose.wto';
function copyAddressBook(name, email) {
	try {
		jsoplog.ucCapture('write_address');
	} catch(e) {}
	if (!Element.visible($(src_focus_id).parentNode.parentNode)) {
		return;
	}
	var _obj = $(src_focus_id);
	// fix 传情计划bug
	if(_obj.value.startsWith('最多18个收件人')) _obj.value = '';
	_obj.focus();
	var _f_addr = ('\"' + name + '\"') + ('\<' + email + '\>');
	if (!_obj.value.toLowerCase().include(_f_addr.toLowerCase())) {
		var cv = _obj.value.strip();
		if (cv == "") {
			_obj.value += _f_addr + ',';
		} else {
			if (cv[cv.length - 1] != "," && !cv.include(",")) {
				_obj.value += ',' + _f_addr + ',';
			} else {
				_obj.value += _f_addr + ',';
			}
		}
	}
}

// 重写prototype中的evalJSON这个函数（FF浏览器的eval性能不是很好）
String.prototype.evalJSON = function(sanitize) {
	try {
		if(JSON && typeof JSON.parse == 'function') {
			return JSON.parse(this);
		}
	} catch(e) {}
	var json = this.unfilterJSON();
	try {
	  if (!sanitize || json.isJSON()) {
	  	if (Prototype.Browser.Gecko) {
			return new Function('return ' + json)();
		} else {
			return eval('(' + json + ')');
		}
	  }
	} catch (e) { }
	throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
};

// onresize事件采用setInterval替代
var Wresize = Class.create();
Wresize.prototype = {
	initialize: function() {
		this.sz = {x:0, y:0};
		this.timer = null;
		this.time = 500;
	},
	pos: function() {
		return {x:document.body.clientWidth, y:document.body.clientHeight};
	},
	fire: function(fn) {
		var self = this;
		this.timer = setInterval(function() {
			if(self.sz.x != self.pos().x || self.sz.y != self.pos().y) {
				fn();
				self.sz = self.pos();
			}
		}, this.time);
	},
	destroy: function() {
		if(this.timer) {
			clearInterval(this.timer);
			this.timer = null;
		}
	}
};
var wresize = new Wresize();

// 格式化FOLDER，使FOLDER中的数据信息和界面显示的一致
(function() {
	try {
		if (FOLDER) {
			var _txt = FOLDER.evalJSON();
			_txt.folders.each(function(item){
				if (item.folder_id == 3) 
					item.name = '已发送';
				if (item.folder_id == 4) 
					item.name = '已删除';
			});
			FOLDER = Object.toJSON(_txt);
		}
	} catch(e) {}
})();

// 获得location的相关属性
function getLocation() {
	try {
		var _f = window.location.href.split('/');
		_f = _f[_f.length - 1];
		if (_f.indexOf('#') != -1) {
			_f = _f.split('#');
			_f = _f[0];
		}
		if (_f.indexOf('?') != -1) {
			_f = _f.split('?');
			_f = _f[0];
		}
		return Object.extend(window.location, {
			folder: _f
		});
	} catch(e) {
		return window.location;
	}
}

// 阻止事件的冒泡，并且隐藏菜单的显示
function eventStop(event) {
	Event.stop(event);
	try {
		if(menu) menu.closeMenu();
	} catch(e) {}
}

// 载入邮箱的广告
function loadSohuMailAds(callback, charset) {
	try {
		if(typeof sohuMailAds == 'undefined') {
			// 根据邮箱选择载入相应的广告碎片代码(目前搜狗的js广告文件是单独的，sohu和chinaren共用一个sohuMailAds.js文件)
			var _url = USE_SYS.name == 'sogou' ? 'sogouMailAds.js' : 'sohuMailAds.js';
			loadScript('http://ad.mail.sohu.com/mail/'+ _url +'?' + load_ads_rand, callback, charset);
		}
	} catch(e) {}
}

// 发信的时候防止垃圾邮件 key的生成
function genKeyCode(){
    mail_send_e._sendtime=(new Date()).getTime();
    return mail_send_e._sendtime;
}

// 格式化发件人地址
function getSenderName(from, show_addr) {
	try {
		if (from[0].blank() && from[1].blank()) {
			return '未知邮件地址';
		} else if(from[0].blank()) {
			return from[1];
		} else if(from[1].blank()) {
			return from[0];
		} else {
			if (show_addr) {
				return from[0] + '&lt;' + from[1] + '&gt';
			} else {
				return from[0];
			}
		}
	} catch(e) {
		return '未知邮件地址';
	}
}

// 判断当前的账号是否为系统账号
function getSysAccount(email) {
	var _j1 = function(_e) {
		try {
			return _e.startsWith('sohumail') && _e.endsWith('mail.sohu.com') && (_e.substring(8, 12) == '1004');
		} catch(e) {
			return false;
		}
	};
	var _j2 = function(_e) {
		try {
			return _e.startsWith('sohumail') && _e.endsWith('mail.sohu.com') && (_e.substring(8, 12) == '1009');
		} catch(e) {
			return false;
		}
	};
	
	var _j_list = [{
		j: email.strip().toLowerCase() == 'webmaster@' + localPostfix,
		r: {
			icon: 'icon_score',
			color: '',
			name: USE_SYS.title + '闪电邮箱'
		}
	}, {
		j: email.strip().toLowerCase() == 'sohumail@' + localPostfix,
		r: {
			icon: 'icon_sys',
			color: '#005BA2',
			name: USE_SYS.title + '邮件中心'
		}
	}, {
		j: email.strip().toLowerCase() == 'mailcenter@' + localPostfix,
		r: {
			icon: 'icon_sys',
			color: 'red',
			name: USE_SYS.title + '邮件中心'
		}
	}, {
		j: email.strip().toLowerCase() == 'admin@' + localPostfix,
		r: {
			icon: 'icon_score',
			color: '',
			name: USE_SYS.title + '邮箱'
		}
	}, {
		j: _j1(email),
		r: {
			icon: 'icon_score',
			color: '',
			name: USE_SYS.title + '闪电邮箱'
		}
	}, {
		j: _j2(email),
		r: {
			icon: 'icon_sys',
			color: '',
			name: USE_SYS.title + '邮件中心'
		}
	}
	];
	
	try {
		var _j = false;
		_j_list.each(function(item) {
			if(item.j && !_j) _j = item.r;
		});
		return _j;
	} catch(e) {
		return false;
	}
}

// 获取直邮的账号
function getZhiYouAccount(email) {
	if(typeof email != 'string') return false;
	try {
		return email.startsWith('sohumail') && email.endsWith('@mail.sohu.com');
	} catch(e) {
		return false;
	}
}

// 格式化系统的昵称
function formatSysAccount(from) {
	if(from[1].include('sohumail@' + localPostfix) || (from[1].startsWith('sohumail') && from[1].endsWith('mail.sohu.com') && (from[1].substring(8, 12) == '1009'))) {
		return ['搜狐邮件中心', ''];
	} else if(from[1].include('webmaster@' + localPostfix) || (from[1].startsWith('sohumail') && from[1].endsWith('mail.sohu.com') && (from[1].substring(8, 12) == '1004'))) {
		return ['搜狐闪电邮箱', ''];
	} else if(from[1].startsWith('sohumail') && from[1].endsWith('mail.' + localDomain)) {
		return [from[0], ''];
	} else {
		return from;
	}
}

// 信纸、明信片图片滚动的一个效果库
var ScrollAnimation = Class.create();
ScrollAnimation.prototype = {
	// id: 被滚动元素块的ID
	// distance: 每次滚动的距离
	// time: 每次滚动花费的时间
	initialize: function(id, distance, time) {
		this.id = id;
		this.el = $(id);
		this.el_width = this.el.getWidth();
		this.pel = this.el.parentNode;
		this.dis = distance ? distance : 86;
		this.time = time ? time : 1000;
		this.timer = null;
		this.ismoving = false;
	},
	scrollLeft: function() {
		this.scroll('left');
	},
	scrollRight: function() {
		this.scroll('right');
	},
	// direction: 滚动方向：left-左、right-右
	scroll: function(direction) {
		if(this.ismoving) return false;
		if(this.timer) {
			try {
				clearInterval(this.timer);
				this.timer = null;
			} catch(e) {}
		}
		var _j = null;
		if(direction == 'right') {
			_j = ((this.pel.scrollLeft + Element.getWidth(this.pel)) >= $(this.id).getWidth());
		} else {
			_j = (this.pel.scrollLeft <= 0);
		}
		if(_j) return false;
		var _index = 0, self = this, _item = this.dis/10, _scroll_left = this.pel.scrollLeft, _sp = self.pel;
		var _t = [12, 32, 52, 68, 80, 86], _index = 0, _n_t = [];
		// var _t = wheel ? [36, 96, 156, 204, 240, 258] : [12, 32, 52, 68, 80, 86], _index = 0, _n_t = [];
		_t.each(function(item, index) {
			_n_t[index] = (direction == 'right') ? (_scroll_left + item): (_scroll_left - item);
		});
		this.ismoving = true;
		this.timer = setInterval(function() {
			if (_index == 6) {
				self.ismoving = false;
				try {
					clearInterval(self.timer);
					self.timer = null;
				} catch(e) {}
				return;
			}
			_sp.scrollLeft = _n_t[_index];
			_index ++;
		}, 30);
	},
	// 鼠标的滚轮事件
	mouseWheel: function() {
		var self = this, direct = 'right';
		var scrollfunc = function(event) {
			Event.stop(event);
			if (event.wheelDelta) {
                direct = event.wheelDelta > 0 ? 'left' : 'right';
            } else if (event.detail) {
                direct = event.detail < 0 ? 'left' : 'right';
            }
			self.scroll(direct);
		};
		try {
			Event.stopObserving(this.pel, 'mousewheel');
		} catch(e) {}
		try {
			Event.stopObserving(this.pel, 'DOMMouseScroll');
		} catch(e) {}
		try {
			Event.observe(this.pel, 'mousewheel', scrollfunc);
		} catch(e) {}
		try {
			Event.observe(this.pel, 'DOMMouseScroll', scrollfunc);
		} catch(e) {}
	},
	// 滑入、滑出的动画效果
	slideDown: function(el, height, slideEnd) {
		this.slide(el, height, 'down', slideEnd);
	},
	slideUp: function(el, height, slideEnd) {
		this.slide(el, height, 'up', slideEnd);
	},
	slide: function(el, height, direction, slideEnd) {
		if(this.ismoving) return false;
		var _el = $(el);
		var __h = direction == 'down' ? '1px' : 'auto';
		_el.setStyle({
			overflow:'hidden',
			height: __h,
			display: 'block'
		});
		this.ismoving = true;
		var _h = height, 
		_item = 5,
		_index = direction == 'down' ? 0 : parseInt(_h/_item)+1, 
		self = this;
		this.timer = setInterval(function() {
			var _j = null, _hh = 0;
			direction == 'down' ? (function() {
					_index ++;
					_hh = _index*_item;
					_j = (_hh >= _h);
				})() : (function() {
					_index --;
					_hh = _index*_item;
					_j = (_hh <= 0);
				})();
			if(_j) {
				self.ismoving = false;
				direction == 'down' ? 
					_el.style.height = 'auto' :
					_el.style.display = 'none';
				if(slideEnd && typeof slideEnd == 'function') {
					slideEnd();
				}
				try {
					clearInterval(self.timer);
					self.timer = null;
				} catch(e) {}
				return false;
			}
			_el.style.height = _hh + 'px';
		}, 30);
	}
};

// 初始化历史记录
function initAjaxHistory() {
	if (Prototype.Browser.IE) {
		// IE下历史记录的初始化
		try {
			ajaxHistoryIE.init(isDomain ? localDomain : undefined);
		} catch(e) { }
	} else {
		try {
			// 历史纪录改变回调函数
			var historyChange = function(newLocation, historyData){
				var historyMsg = (typeof historyData == "object" && historyData != null ? historyData.toJSON() : historyData);
				eval(historyData);
			};
			dhtmlHistory.addListener(historyChange);
		} catch(e) {}
	}
}

// 创建载入地址本其他信息的iframe
function createAddrOthers() {
	var _div = document.createElement('div');
	Element.setStyle(_div, {
		position: 'absolute',
		zIndex: 1000000,
		top: '-2000px',
		left: '-2000px',
		width: '1px',
		height: '1px'
	});
	document.body.appendChild(_div);
	var set_dm = isDomain ? 'document.domain=\'' + localDomain + '\';' : '';
	var _url = _otherAddrData.url + '?' + (+new Date());
	var _other_data = '<iframe name="otherAddrData" id="otherAddrData" src="javascript:document.open(\'text\/html\',\'replace\');'+ set_dm +'document.write(\'<head><meta http-equiv=Content-Type content=text/html;charset=utf-8 /><script src='+ _url +'></script></head><body></body>\');document.close();"></iframe>';
	_div.innerHTML = _other_data;
}

function createAddrOthersCallback() {
	_otherAddrData.loaded = true;
}

// 地址簿其他信息的载入
try {
	createAddrOthers();
} catch(e) {}

// 如果用户邮箱的容量超出总容量，提示用户不能进行写信的操作了
function listenVolume() {
	try {
		if(FoldersData.totalSize >= mailContentTotalSize) {
			_dialog.alert({info: '您使用的容量已经超出邮箱容量的总大小，这样将会导致您不能成功发信，请删除部分不需要的邮件，并且退出后重新登录~'});
			return false;
		} else {
			return true;
		}
	} catch(e) {
		return true;
	}
}

// 获取滚动条的宽度
function getScrollBarWidth() {
	var div1 = document.createElement('div');
	Element.setStyle(div1, {
		width: '100px',
		height: '200px',
		overflow: 'auto',
		position: 'absolute',
		left: '-1000px',
		right: '-1000px',
		display: 'block'
	});
	div1.innerHTML = '<div style="width:200px;height:200px;display:block;"></div>';
	document.body.appendChild(div1);
	div1.scrollTop = 100;
	var sbw = div1.scrollTop;
	div1.parentNode.removeChild(div1);
	div1 = null;
	return sbw;
}

// 根据界面元素的实际宽高重置一些默认值
function resetStaticValue() {
	// 根据clientWidth获取元素的宽度属性是只有当前元素被看到的时候，才能取到，这个问题prototype.js也没有给出更好的修复
	staticValue.leftWidth = parseInt((DOM.left ? DOM.left : DOM.left=$('left'),DOM.left).getStyle('width'));
	staticValue.scrollBar = getScrollBarWidth();
}
resetStaticValue();

// 是邮箱系统左侧的操作栏在界面固定
function leftOperateFixed() {
	var _ab = DOM.sohuMailMain ? DOM.sohuMailMain : $('sohuMailMain'),
	_lo = DOM.left ? DOM.left : $('left'),
	_ot = _lo.offsetTop;
	Event.observe(_ab, 'scroll', function(event) {
		if(_ab.scrollTop >= _ot) {
			_lo.setStyle({
				position:'fixed',
				top:0
			});
		} else {
			_lo.setStyle({
				position:'',
				top:''
			});
		}
	});
}

// 进入会话模式的快捷入口按钮
function tryConferenceMode() {
	try {
		if (!DOM.is_use_con) DOM.is_use_con = $('is_use_con');
		DOM.is_use_con.addClassName('am use-con s_overview_c');
		DOM.is_use_con.innerHTML = '体验会话模式';
	} catch(e) {}
}

// 右下浮动广告的载入
var FloatADS = {
	ads: null,
	pos: {width:141, height:96},
	isShow: true,
	timer: null,
	floatads: function(){
		try {
			return (sohuMailAds && sohuMailAds.floatads) ? (sohuMailAds.floatads.show ? sohuMailAds.floatads : null) : null;
		} catch(e) {
			return null;
		}
	},
	// imgurl: 'http://images.sohu.com/freemail/2009mailad/091020youshang/float_ads.1020.png',
    show: function(){
		if(!this.floatads) return false;
		var _ads = this.floatads();
		if(!_ads) return false;
		if(!(_ads.href && _ads.img) || (_ads.href.strip() == '' && _ads.img.strip() == '')) return false;
		if(PROFILE.ads_flag) return false;
		if(USE_SYS.name != 'sohu') return false;
		if(!this.isShow) return false;
        if(!this.ads) this.ads = $('float_ads');
        if (!this.ads) {
			// 注： 本来可以用一个div搞定的问题，用了多个div来实现，为了兼容IE6 ..............
            var _div = document.createElement('div');
            _div.setAttribute('id', 'float_ads');
			var _div1 = document.createElement('div');
			Element.setStyle(_div1, {
				width: '100%',
				height: '100%',
				backgroundColor: 'transparent',
				position: 'absolute',
				zIndex: 2,
				cursor: 'pointer'
			});
			var _div2 = document.createElement('div');
			Element.setStyle(_div2, {
				position: 'absolute',
				left: '0px',
				top: '0px',
				width: '100%',
				height: '100%',
				zIndex: 1
			});
			if(Prototype.Browser.IE) {
				_div2.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+ _ads.img +'")';
			} else {
				_div2.style.backgroundImage = 'url(\'' + _ads.img + '\')';
				_div2.style.backgroundRepeat = 'no-repeat';
			}
            Element.setStyle(_div, {
                width: this.pos.width + 'px',
                height: this.pos.height + 'px',
                position: 'absolute',
                zIndex: '9999999',
                right: '0px',
                bottom: '6px',
				backgroundColor: 'transparent',
                color: 'white',
                display: 'none'
            });
			_div.appendChild(_div1);
			_div.appendChild(_div2);
            _div1.innerHTML = '<a style="float:right;margin:2px 18px auto auto;filter:none;" href="javascript:;">关闭</a><a href="'+ _ads.href +'" style="height:70px;width:100%;display:block;" target="_blank" hidefocus="true">&nbsp;</a>';
			if (Prototype.Browser.IE) {
				DOM.sohuMailMain.appendChild(_div);
				this.timer = setInterval(function() {
					Element.setStyle(_div, {
						top: (DOM.sohuMailMain.offsetHeight + DOM.sohuMailMain.scrollTop - 96) + 'px',
						bottom: 'auto'
					});
				}, 200);
			} else {
				document.body.appendChild(_div);
				Element.setStyle(_div, {
					right: '18px'
				});
			}
			this.isShow = false;
			this.setTime();
			var self = this;
			Event.observe(_div1.firstChild, 'click', function(event) {
				try {
					self.hide();
				} catch(e) {}
				try {
					self.isShow = false;
				} catch(e) {}
				try {
					clearInterval(self.timer);
					self.timer = null;
				} catch(e) {}
				try {
					jsoplog.ucCapture('closegift');
				} catch(e) {}
				self.setTime();
				Event.stop(event);
				return false;
			});
			// 加一个log统计
			Event.observe(_div1.firstChild.nextSibling, 'click', function(event) {
				try {
					jsoplog.ucCapture('getgift');
				} catch(e) {}
				return false;
			});
            this.ads = _div;
        }
		var _mb = 0 - this.pos.height;
        Element.setStyle(this.ads, {
			marginBottom: _mb + 'px',
            display: ''
        });
        var _index = _mb, self = this;
        var _si = setInterval(function(){
            if (_index >= 0) {
                clearInterval(_si);
                _si = null;
				var _i = 0;
				var _t = setInterval(function() {
					if(_i > 4) {
						clearInterval(_t);
						_t = null;
						return false;
					}
					if(_i%2 != 0) {
						Element.setStyle(self.ads, {opacity: 0.3});
					} else {
						Element.setStyle(self.ads, {opacity: 1});
					}
					_i++;
				}, 100);
            } else {
                Element.setStyle(self.ads, {
                    marginBottom: _index + 'px'
                });
                _index += 6;
            }
        }, 30);
    },
	hide: function() {
		if(this.ads) {
			Element.hide(this.ads);
		}
	},
	setTime: function() {
		try {
			profile_set({ads_day: new Date().getTime()}, function(ret) {
				PROFILE.ads_flag = true;
			});
		} catch(e) {}
	}
};

// mail中用到的一些动画效果（scriptaculous.js这个库有的没有实现，或者实现的不好）
var MailEffect = {
	sinoidal: function(pos) {
      return (-Math.cos(pos*Math.PI)/2) + .5;
    },
	SlideDown: function(el, options) {
		el = $(el);
		var _y = el.getHeight();
		var o = {
			time: 30,
			distance: 5
		};
		options = options ? options : {};
		options = Object.extend(o, options);
		var _index = 0;
		el.setStyle({height: _index + 'px'});
		var _t = setInterval(function() {
			if(_index >= _y) {
				clearInterval(_t);
				_t = null;
				el.setStyle({height: _y + 'px'});
				try {
					Element.setStyle(el.getElementsByTagName('a')[0], {
						display: 'block'
					});
				} catch(e) {}
				return false;
			}
			el.setStyle({height: _index + 'px'});
			_index += options.distance;
		}, options.time);
	},
	SlideRight: function(el, options) {
		el = $(el);
		var _x = el.getWidth();
		var o = {
			time: 30,
			distance: 15
		};
		options = options ? options : {};
		options = Object.extend(o, options);
		var _index = 0;
		el.setStyle({width: _index});
		var _t = setInterval(function() {
			if(_index >= _x) {
				clearInterval(_t);
				_t = null;
				el.setStyle({width: _x + 'px'});
				try {
					Element.setStyle(el.getElementsByTagName('a')[0], {
						display: 'block'
					});
				} catch(e) {}
				return false;
			}
			el.setStyle({width: _index + 'px'});
			_index += options.distance;
		}, options.time);
	},
	Appear: function(el, options) {
		el = $(el);
		var o = {
			time: 30,
			opacity: 0.05
		};
		options = options ? options : {};
		options = Object.extend(o, options);
		var _index = 0;
		el.setStyle({opacity: _index});
		var _t = setInterval(function() {
			if(_index >= 1) {
				clearInterval(_t);
				_t = null;
				el.setStyle({opacity: 1});
				try {
					Element.setStyle(el.getElementsByTagName('a')[0], {
						display: 'block'
					});
				} catch(e) {}
				return false;
			}
			el.setStyle({opacity: _index});
			_index += options.opacity;
		}, options.time);
	}
};

// Effect动画库的扩展
(function() {
	try {
		if(!Effect) return false;
		Effect.BlindLeft = function(element) {
  			element = $(element);
  			var elementDimensions = element.getDimensions();
  			return new Effect.Scale(element, 100, Object.extend({
    			scaleContent: false,
    			scaleX: true,
				scaleY: false,
    			scaleFrom: 0,
    			scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    			restoreAfterFinish: true,
    			afterSetup: function(effect) {
      				effect.element.makeClipping().setStyle({width: '0px'}).show();
    			},
    			afterFinishInternal: function(effect) {
      				effect.element.undoClipping();
    			}
  			}, arguments[1] || { }));
		};
		Effect.BlindRight = function(element) {
  			element = $(element);
  			var elementDimensions = element.getDimensions();
  			return new Effect.Scale(element, 0, Object.extend({
    			scaleContent: false,
    			scaleX: true,
				scaleY: false,
    			restoreAfterFinish: true,
    			afterSetup: function(effect) {
      				effect.element.makeClipping();
    			},
    			afterFinishInternal: function(effect) {
      				effect.element.hide().undoClipping();
    			}
  			}, arguments[1] || { }));
		};
	} catch(e) {}
})();

// element的一个扩展，根据classname找到某个元素父级元素
Element.getParentNodeByClassName = function(element, cname, piece) {
	element = $(element);
	if(!element || !cname || cname == '') return null;
	try {
		while(element) {
			if(piece && element.className.include(cname)) return element;
			else if (Element.hasClassName(element, cname)) return element;
			element = element.parentNode;
		};
	} catch(e) {
		return null;
	}
};
// 根据tagname找到某个元素的父级元素
Element.getParentNodeByTagName = function(element, tname) {
	element = $(element);
	if(!element || !tname || tname == '') return null;
	try {
		while(element) {
			if (element.tagName.toLowerCase() == tname) return element;
			element = element.parentNode;
		};
	} catch(e) {
		return null;
	}
};
// 根据节点上的属性找到某个元素的父级元素
Element.getParentNodeByAttribute = function(element, attr) {
	element = $(element);
	if(!element || !attr || attr == '') return null;
	try {
		while(element) {
			var _attr = element[attr] ? element[attr] : element.getAttribute(attr);
			if (_attr && _attr != '') return {
					element: element,
					attribute: _attr
				};
			element = element.parentNode;
		};
	} catch(e) {
		return null;
	}
};

// 键盘快捷键操作
function initShortCuts() {
	var mtn = function() {
		// 读信界面
		if(!DOM.readMail.visible()) return false;
		try {
			if (isConferenceMode) {
				if(PREV_ID) mailConference.getMailRead(PREV_ID);
				else mailConference.rtListPage();
			} else {
				if(PREV_ID) mailRead.getMailRead(PREV_ID);
				else mailRead.rtListPage();
			}
		} catch(e) {}
	}, mto = function() {
		// 读信界面
		if(!DOM.readMail.visible()) return false;
		try {
			if (isConferenceMode) {
				if(NEXT_ID) mailConference.getMailRead(NEXT_ID);
				else mailConference.rtListPage();
			} else {
				if(NEXT_ID) mailRead.getMailRead(NEXT_ID);
				else mailRead.rtListPage();
			}
		} catch(e) {}
	};
	var ke = {
		// Move to newer conversation (k)
		'75': mtn,
		// '37': mtn,
		// Move to older conversation (j)
		'74': mto,
		// '39': mto,
		// Compose (c)
		'67': function() {
			if(DOM.composeMail.visible()) return false;
			changePanel('composeMail');
		},
		// Report spam (!)
		'49 shiftKey': function() {
			// if(!DOM.readMail.visible() && !DOM.mailList.visible()) return false;
			try {
				if(isConferenceMode) {
					var mc = mailConference;
					if (DOM.mailList.visible()) {
						if (mc.folder != 2 && mc.folder != 3) {
							mc.delMailInList('spam');
						}
					} else if (DOM.readMail.visible()) {
						if (mc.folder != 2 && mc.folder != 3 && mc.folder != 5) {
							var ids = [];
							mc.currentConference.each(function(item){
								ids.push(item.rowid);
							});
							mc.delMail(ids, 'spam');
						}
					}
				} else {
					var ml = mailList, mr = mailRead;
					if (DOM.mailList.visible()) {
						if (ml.currentFolder != 2 && ml.currentFolder != 3 && ml.currentFolder != 5) {
							ml.spamMailItems();
						}
					} else if(DOM.readMail.visible()) {
						if(mr.folder != 2 && mr.folder != 3 && mr.folder != 5) {
							mr.mailMove(-1, 3);
						}
					}
				}
			} catch(e) {}
		},
		// Reply (r)
		'82': function() {
			if(!DOM.readMail.visible()) return false;
			try {
				var mc = mailConference, mr = mailRead;
				if(isConferenceMode) {
					mc.replyMail(mc._last_id, 'reply');
				} else {
					mr.replyMail('reply');
				}
			} catch(e) {}
		},
		// Reply all (a)
		'65': function() {
			if(!DOM.readMail.visible()) return false;
			try {
				var mc = mailConference, mr = mailRead;
				if(isConferenceMode) {
					mc.replyMail(mc._last_id, 'replyall');
				} else {
					mr.replyMail('replyall');
				}
			} catch(e) {}
		},
		// Forward (f)
		'70': function() {
			if(!DOM.readMail.visible()) return false;
			try {
				var mc = mailConference, mr = mailRead;
				if(isConferenceMode) {
					mc.replyMail(mc._last_id, 'forward');
				} else {
					mr.replyMail('forward');
				}
			} catch(e) {}
		},
		// Delete (#)
		'51 shiftKey': function() {
			try {
				if(isConferenceMode) {
					var mc = mailConference;
					if (DOM.mailList.visible()) {
						if(mc.folder != 2 && mc.folder != 3 && mc.folder != 4) {
							mc.delMailInList('del');
						}
					} else if(DOM.readMail.visible()) {
						if(mc.folder != 2 && mc.folder != 3 && mc.folder != 4) {
							var ids = [];
							mc.currentConference.each(function(item){
								ids.push(item.rowid);
							});
							mc.delMail(ids, 'del');
						}
					}
				} else {
					var ml = mailList, mr = mailRead;
					if (DOM.mailList.visible()) {
						if(ml.currentFolder != 2 && ml.currentFolder != 3 && ml.currentFolder != 4) {
							ml.deleteMailItems();
						}
					} else if(DOM.readMail.visible()) {
						if(mr.folder != 2 && mr.folder != 3 && mr.folder != 4) {
							mr.mailMove(4);
						}
					}
				}
			} catch(e) {}
		}
	};
	$(document).observe('keyup', function(event) {
		var el = event.target;
		if(el.nodeName.toLowerCase() == 'input') {
			Event.stop(event);
			return false;
		}
		var k = event.keyCode, sk = event.shiftKey, ck = event.ctrlKey, ak = event.altKey,
		sk_t = sk ? ' shiftKey' : '', ck_t = ck ? ' ctrlKey' : '', ak_t = ak ? ' altKey' : '';
		k += sk_t + ck_t + ak_t;
		var kef = ke[k];
		if(kef && typeof kef == 'function') {
			kef();
		}
	});
}

// 向prototype.js中的Element对象添加方法
/*
Object.extend(Element.Methods, {
	getParentNodeByClassName: function(element, cname, piece) {
		element = $(element);
		if(!element || !cname || cname == '') return null;
		try {
			while(element) {
				if(piece && element.className.include(cname)) return element;
				else if (Element.hasClassName(element, cname)) return element;
				element = element.parentNode;
			};
		} catch(e) {
			return null;
		}
	},
	getParentNodeByTagName: function() {
		
	}
});
*/


// fix ie 不存在console的问题
try {
	if (!console) {
		var console = {log: function() {}};
		console.log = function(msg){
			try {
				console.log(msg);
			} catch (e) { }
		};
	}
} catch(e) {}

/////////根据url获取参数////////
function getParametersFromUrl(){
  var params = {};
  var queryString = window.location.hash;
  var i = queryString.indexOf("?");
  if(i<0){
    G.ANCHOR_PARAMETERS = params;
    return params;
  }
  var q = queryString.substring(i+1);
  var arr = q.split("&");
  var n = arr.length;
  for (var i=0;i<n ;i++ ){
    if(!arr[i])
      continue;
    var p = arr[i].split("=");
    if(!p)
      continue;
    var k = p[0];
    var v = p.length>1?unescape(p[1]):null;
    if(!params[k])
      params[k] = [v];
    else
      params[k].push(v);
  }
  G.ANCHOR_PARAMETERS = params;
  return params;
}
//相应左侧网络优盘事件
function showUdiskPanel(){
    if (G.hasUDiskRights()){
        return true;
    }
    hiddenAllPanel();
    var tem = new Template(udiskTemplate);
    var data = new Object();
    $('mailConfiguration').innerHTML = tem.evaluate(data);
    $('mailConfiguration').show();
    return false;
}
//打开遮罩
function CreateFullPageMask( handle ){
    var h = 0;
    try{
        if( handle == undefined || handle == null ){
                h = $('nav').getHeight() + $( 'composeMail').getHeight() + 70;
        }
        else{
            h = $('nav').getHeight() + $( 'readMail').getHeight() + 70;
        }
    } catch(e ){
        try {
            h = $('nav').getHeight() + $( 'readMail').getHeight() + 70;
        } catch( e ){}
    }

    var div = '<div id="div4FullPage" style="background:#CCCCCC;filter:Alpha(opacity=30);-moz-opacity:0.30;position:absolute;top:0px;left:0px;width:100%;height:'+ h +'px;z-index:9999;"><span> &nbsp; </span></div>';
    Element.insert($('sohuMailMain'), {bottom: div});
    Element.setStyle($('div4FullPage'), {filter:'Alpha(opacity=30)',opacity:0.3,mozOpacity:0.3,khtmlOpacity:0.3});
}
//关闭遮罩
function removeFullPageMask(){
    try{        
        $( 'div4FullPage' ).remove();
    }catch(e){
        $( 'div4FullPage' ).remove();
        alert( e );
    }
}

function initMobileUserInfo(){
    getMobileUserInfo({}, function(data){
    	try{
        	//G.setMobileUser(1);
            G.setMobileUser(data["mobileuser"]);
        } catch(e){}
    });
}

function initUdiskUserService(){
	if(USE_SYS.name != 'sohu' && USE_SYS.name != 'vip.sohu') return false;
    getUDiskUserService(
        // {userid: UserSohuID} ,
		{},
        function(data){
            if(data["status"]==0 && parseInt(data["serverid"])>0){
                G.UDISK_SERVERID = data["serverid"];
				G.UDISKUSER = true;
			}
        }
    );
}
